<?php
class Variable{
	public $logic = null;
	public $vars = null;
	public $value = null;
	public $siblings = null;
	
	public function Variable($logic, $vars, $siblings = array()){
		$this->logic = $logic;
		$this->vars = array_merge(
			$vars, 
			array('GET'=>$_GET), 
			array('POST'=>$_POST), 
			array('SERVER'=>$_SERVER),
			array('GLOBALS'=>$GLOBALS)
		);
		$this->siblings = $siblings;
	}
	
	public function evaluate(){
		//parse subvars
		preg_match_all('`\{\$(.*)\}`', $this->logic, $matches);
		if(count($matches[1])){
			foreach($matches[1] as $key => $var_logic){
				$var = new Variable($var_logic, $this->vars);
				$new_logic = str_replace($matches[0][$key], $var->evaluate(), $this->logic);
				$this->logic = $new_logic;
			}
		}
		//parse constant
		$arr = explode(' ',$this->logic);
		preg_match('`CT\[(.*)\]`', $this->logic, $ct_matches);
		if($ct_matches[1] && defined($ct_matches[1])){
			$value = constant($ct_matches[1]);
		}else{
			//parse normal var
			if(strstr($arr[0], '[') && strstr($arr[0],']')){//if is array
				$value = $this->get_var_array($this->vars, $arr[0]);
			}else{//simple var
				$value = $this->vars[$arr[0]];
			}
		}
		if(count($arr)==1) return array('replacement'=>$value);//return if no modifiers
		
		//process modifiers
		$this->value = $value;
		
		//setup for dom object
		unset($arr[0]);
		$logic = implode(' ',$arr);
		$smart_var = '<varname '.$logic.' />';
		$dom = new simple_html_dom;
		$dom->load($smart_var, false);
		$mods = $dom->find('varname', 0);
		
		//apply modifiers
		if($mods->function){
			$functions = explode('|',$mods->function);
			foreach($functions as $f){
				$func_body = strstr($f, '(') ? $f : $f.'(_THIS_)';
				$func_body = str_replace('_THIS_', '$value', $func_body);
				$func_body = str_replace('_SIBLINGS_', '$this->siblings', $func_body);
				$func = '$value = '.$func_body.';';
				eval($func);
			}
		}
		if($mods->inc){$value++;}
		if($mods->dec){$value--;}
		if($mods->default && !$value){
			$value = $mods->default;
		}
		if($mods->del && !$value){
			$ret['tag'] = $mods->del;
		}
		if($mods->ndel && $value){
			$ret['tag'] = $mods->ndel;
		}
		if($mods->pdel && !$value){
			$ret['ptag'] = $mods->pdel;
		}
		if($mods->npdel && $value){
			$ret['ptag'] = $mods->npdel;
		}
		
		$ret['replacement']	= $value;
		return $ret;
	}
	
	public function get_var_array($vars, $str){
		$tmp = explode('[',$str);
		$var_name = $tmp[0];
		$var_indexes = substr($str, strlen($var_name));
		return $this->var_array($vars[$var_name], $var_indexes);
	}
	
	public function var_array($arr, $string){
    	preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER);
    	$return = $arr;
    	foreach($arr_matches[1] as $dimension){
        	$return = $return[$dimension];
        }
    	return $return;
    }
}
?>